<?php
namespace App\Http\Controllers\BG;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redis;

use  App\Models\User;

use Illuminate\Support\Facades\DB;
use Cache;
use Validator;
use Carbon\Carbon;
use function GuzzleHttp\json_decode;


class LoginController extends Controller
{
    public function login(Request $request)
    {
        $input = Input::only('phone', 'pw','type');
        $validator = Validator::make($input, [        
            'phone'      => 'required|string',
            'pw'     => 'required',
            'type'   => 'required'
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $data['phone'] = $input['phone'];
        $data['pw'] = $input['pw'];
        $where['phone'] = $input['phone'];
        $where['pw'] = md5($input['pw']);
        $exist = User::where($where)->first();
        if($exist){
            if($exist->is_open==0){
                return $this->returnError([],403,'员工已被禁止登陆，请联系管理员');
            }
            $exist->save();
            $str =  str_random(32);
            unset($exist['pw']);
            $exist['type'] = $input['type'];
            Redis::setex($str,720000,json_encode($exist->toArray()));
            $ip = $request->getClientIp();
            $str2 = md5($ip);
            $str3 =  str_random(32);
            Redis::setex($str3,720000,$str2);
            $final = $str.'.'.$str2.'.'.$str3;
            return $this->returnOk($final);
        }else{
            return $this->returnError([],409,'用户不存在');
            
        }
        return $this->returnOk();
    }

    public function info(Request $request)
    {
        $token = $request->header('authorization');
        $key = explode('.',$token);
        $data = Redis::get($key[0]);
        return $this->returnOk(json_decode($data) );
    }

    public function logout(Request $request)
    {
        $token = $request->header('authorization');
        $key = explode('.',$token);
        Redis::del($key[0]);
        return $this->returnOk([]);
    }
}